/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.commons.util;

import java.util.Collection;

/**
 * A simple Filter based on a collection.
 * 
 * @author Yann D'Isanto
 */
public class DefaultFilter<T> implements Filter<T> {

    private Collection<T> collection;
    private boolean rejectOnMatch;

    /**
     * Creates a filter based on the specified collection. Values are accepted 
     * if they are contained in the collection.
     * @param collection the collection.
     */
    public DefaultFilter(Collection<T> collection) {
        this(collection, true);
    }

    /**
     * Creates a filter based on the specified collection. The specified 
     * acceptOnMatch flag defines if the collection represents accepted or 
     * rejected values.
     * @param collection the collection.
     * @param acceptOnMatch accept on match flag.
     */
    public DefaultFilter(Collection<T> collection, boolean acceptOnMatch) {
        this.collection = collection;
        this.rejectOnMatch = !acceptOnMatch;
    }

    @Override
    public boolean accept(T t) {
        return collection.contains(t) ^ rejectOnMatch;
    }

    /**
     * Returns the collection defining accepted/rejected values.
     * @return the collection defining accepted/rejected values.
     */
    public Collection<T> getCollection() {
        return collection;
    }

    /**
     * Sets the collection defining accepted/rejected values.
     * @param collection the collection.
     */
    public void setCollection(Collection<T> collection) {
        this.collection = collection;
    }

    /**
     * Returns true if this filter collection represents accepted values, false 
     * otherwise.
     * @return 
     */
    public boolean isAcceptOnMatch() {
        return !rejectOnMatch;
    }

    /**
     * Specifies if this filter collection represents accepted or rejected values.
     * @param acceptOnMatch accept on match flag.
     */
    public void setAcceptOnMatch(boolean acceptOnMatch) {
        this.rejectOnMatch = !acceptOnMatch;
    }
}
